<template>
  <div class="login-container">
    <div class="bg2">

    </div>
    <video src="../../assets/video/bg-video.d2d602a9.mp4"
           autoplay='true'
           loop='loop'
           muted></video>
    <el-form :model="loginForm"
             status-icon
             :rules="rules"
             ref="loginForm"
             label-width="100px"
             class="demo-loginForm">
      <h1 class="title">千分学员管理</h1>
      <!-- 常规登录 必须用v-if v-else 因为第一次切换要刷新二维码
      不然就会出现二维码过期
      -->
      <div class="commen-login"
           v-if='!isewm'>
        <i @click="isewm=!isewm"
           :class="['iconfont',isewm?'icon-erweimajiaobiao':'icon-diannao']"></i>
        <el-form-item label="用户名"
                      prop="username">
          <el-input type="text"
                    v-model="loginForm.username"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码"
                      prop="passworld">
          <el-input type="password"
                    v-model="loginForm.passworld"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="验证码"
                      prop="captcha">
          <el-input v-model="loginForm.captcha"
                    class="captcha"
                    ref='captchaipt'
                    @keydown.native.enter="submitForm('loginForm')"></el-input>
          <!-- 输入框原生触发enter事件 -->
          <span class="captcha-svg"
                v-html='captchaSvg'
                @click="updatecaptcha"></span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"
                     @click="submitForm('loginForm')">提交</el-button>
        </el-form-item>
      </div>
      <!-- 切换二维码登录 -->
      <div v-else>
        <i @click="isewm=!isewm"
           :class="['iconfont',isewm?'icon-erweimajiaobiao':'icon-diannao']"></i>
        <div class="qrdiv">
          <img :src="qrimg"
               alt="">
          <div v-text="tips"></div>
          <i class="mask"
             :style="qrstyle"
             v-show="issaoma"></i>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
  import {
    loginapi,
    getCaptcatapi,
    verifyCaptchaapi, getwechatqrcode, wechatapi
  } from "../../api/index"
  import { mapMutations, mapState, mapActions } from 'vuex'
  import io from 'socket.io-client'
  import qrcode from 'qrcode'
  import sucessimg from '../../assets/img/成功.png'
  import invalidimg from '../../assets/img/失败.png'
  export default {
    data() {
      var validateCapticha = (rule, value, callback) => {
        if (value.length !== 5) {
          callback('验证码必须5位数')
        } else {
          callback()
        }

      };
      var validateUsername = (rule, value, callback) => {
        if (value) {
          callback()
        } else {
          callback('用户名不能为空')
        }
      };
      var validatePass = (rule, value, callback) => {
        let reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
        if (value) {
          callback()
        } else {
          callback('长度至少为8，至少含有一个字母和一个数字')
        }
      };
      return {
        loginForm: {
          username: '',
          passworld: '',
          captcha: '',
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          passworld: [
            { validator: validatePass, trigger: 'blur' }
          ],
          captcha: [
            { validator: validateCapticha, trigger: 'blur' }
          ]
        },
        isewm: false,
        captchaSvg: '',
        qrimg: '',
        issaoma: false,
        qrstyle: {
          backgroundImage: `url(${sucessimg})`
        },
        tips: '请使用手机微信扫码登录'
      };
    },

    methods: {
      ...mapActions(['GET_MENULIST']),
      ...mapMutations(["SET_USERINFO"]),
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //调用服务的方式展现loading动画(调用element-ui的loading动画)
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            //先调用验证码api验证
            verifyCaptchaapi(this.loginForm.captcha.toLowerCase())
              .then(res => {
                if (res.data.state) {
                  //验证码正确然后继续获取用户名和密码
                  //调用验证码api验证
                  loginapi(this.loginForm.username, this.loginForm.passworld)
                    .then(res => {
                      //返回登入校验信息
                      if (res.data.state) {
                        //弹出框
                        this.$message({
                          message: '恭喜你，登入成功',
                          type: 'success',
                          duration: 1000,
                        });
                        //将登录的数据存入Vuex
                        this.SET_USERINFO(res.data.userInfo)
                        //将按钮级别的鉴权存入本地
                        localStorage.setItem('permission', JSON.stringify(res.data.permission.buttons))
                        //将token存到本地                     
                        localStorage.setItem('login-token', res.data.token)
                        //将userinfo存到本地
                        localStorage.setItem('userinfo', JSON.stringify(res.data.userInfo))
                        //关闭loading动画
                        loading.close();
                        //跳转到主页
                        this.$router.push('/')
                      } else {
                        //登入失败
                        //alert("账户密码错误")
                        this.$message.error('账户密码错误')
                        loading.close();
                      }
                    })
                } else {
                  //验证码失败重新刷新验证码并清除已输入的内容
                  this.$message.error('验证码错误')//饿了么ui弹窗提示
                  this.loginForm.captcha = ''
                  //让输入框重新获取焦点
                  this.$refs.captchaipt.focus()
                  this.updatecaptcha()
                  loading.close()

                }
              })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //封装验证码函数
      updatecaptcha() {
        getCaptcatapi().then(res => {
          this.captchaSvg = res.data.img;
        })
      }
    },
    created() {
      this.updatecaptcha();
    },
    watch: {
      //监听二维码切换显示字段true就是显示二维码
      isewm(newval, oldval) {
        if (newval) {
          //二维码界面
          //1.通过socket.io和服务器建立连接
          let socket = io('wss://chst.vip')
          //2.监听连接成功事件,发送请求获取二维码地址
          socket.on('connectSuccess', (res) => {
            getwechatqrcode(res.sid).then(res => {
              //3.通过qrcode将二维码地址生成base64二维码图片地址
              qrcode.toDataURL(res.data.scanCodeUrl, (err, dataimg) => {
                this.qrimg = dataimg
                this.issaoma = false
              })
            })
          })
          //4.用户扫描二维码
          //5.监听socket事件(scancodesuccess)这个事件不是socket.io定义的，是前后端约定的，用于获取wechatCode
          socket.on('scancodeSuccess', (res) => {
            //判断是否已经扫码
            if (res.state) {
              //已经扫码
              this.issaoma = true
              //6.请求user/wechatLogin,传递wechatCode
              wechatapi(res.wechatCode).then(res => {
                if (res.data.state) {
                  //将登录的数据存入Vuex
                  this.SET_USERINFO(res.data.userInfo)
                  //将按钮级别的鉴权存入本地
                  localStorage.setItem('permission',JSON.stringify(res.data.permission.buttons))
                  //将token存到本地
                  localStorage.setItem('login-token', res.data.token)
                  //将userinfo存到本地
                  localStorage.setItem('userinfo', JSON.stringify(res.data.userInfo))
                  //跳转到首页
                  this.$router.push('/')
                } else {
                  this.message.error('微信登录失败')
                }

              })
            } else {
              //扫码失败了
              this.message.error('微信扫码失败')
            }
            //7.判断成功和失败
          })
          //监听socket事件
          socket.on("invalidCode", (data) => {
            console.log(data);
            this.qrstyle.backgroundImage = `url(${invalidimg})`; //显示二维码失效的标志
            this.issaoma = true //显示遮罩
            this.tips = "二维码失效,请点击刷新二维码"

          });


        }
      }
    }
  }
</script>

<style lang='scss' scoped>
  .login-container {
  	.bg2 {
  		position: fixed;
  		background-image: url('../../assets/img/bg2.fc58c850.png');
  		background-repeat: no-repeat;
  		width: 20%;
  		height: 40%;
  		/* 图片在盒子中适应等比例缩小 */
  		background-size: 100% 100%;
  		left: 20%;
  		top: 40%;
  		opacity: 0.5;
  		z-index: 99;
  	}
  	video {
  		position: fixed;
  		top: 0;
  		left: 0;
  		right: 0;
  		bottom: 0;
  		/* 当100%设置不上，触发bfc自动适应整个屏幕 */
  		background: url('../../assets/img/bg2.fc58c850.png');
  		background-repeat: no-repeat;
  	}
  	/*  ::v-deep样式穿透因为没有属性选择器 */
  	::v-deep .el-form {
  		position: fixed;
  		left: 65%;
  		top: 25%;
  		background-color: rgba(0, 0, 0, 0.3);
  		color: #fff;
  		padding: 40px 13px 50px 0;
  		width: 400px;
  		border-radius: 15px;
  		.el-input__inner {
  			width: 250px;
  		}
  		.el-button--primary {
  			width: 250px;
  		}
  		.el-form-item__label {
  			color: #fff;
  		}
  	}
  }
  .title {
  	color: #fff;
  	margin: 50px 0 40px 0;
  	text-align: center;
  }
  .icon-diannao,
  .icon-erweimajiaobiao {
  	font-size: 40px;
  	color: #fff;
  	position: absolute;
  	right: -1px;
  	top: -1px;
  	cursor: pointer;
  }
  //验证码样式
  .captcha-svg {
  	background: #fff;
  	display: inline-block;
  	height: 45px;
  	width: 150px;
  	text-align: center;
  	cursor: pointer;
  	border-radius: 0 5px 5px 0;
  }
  //验证码父盒子样式
  .captcha {
  	width: 100px;
  	vertical-align: top;
  	/* 验证码输入框样式 */
  	::v-deep .el-input__inner {
  		width: 100px !important;
  		border-radius: 5px 0 0 5px;
  		height: 45px;
  		border-right: 0;
  	}
  }
  .qrdiv {
  	text-align: center;
  	position: relative;
  	left: 11px;
  	top: -10px;
  	div {
  		position: absolute;
  		left: 24%;
  		bottom: -40px;
  	}
  	.mask {
  		width: 260px;
  		height: 260px;
  		opacity: 0.7;
  		background-color: gray;
  		position: absolute;
  		left: 70px;
  		// background-image: url("../../assets/img/scancode.png");
  		background-size: 50%;
  		background-repeat: no-repeat;
  		background-position: center;
  		cursor: pointer;
  	}
  }
</style>
